package com.ayf.payment.game.api.service.impl;

import com.ayf.payment.game.api.dto.*;
import com.ayf.payment.game.api.dto.criteria.TemplateCriteria;
import com.ayf.payment.game.api.dto.criteria.TemplateGameSelectCriteria;
import com.ayf.payment.game.api.dto.criteria.TemplatePageCriteria;
import com.ayf.payment.game.api.dto.criteria.TemplateSelectCriteria;
import com.ayf.payment.game.api.dto.platform.SettleConfigDTO;
import com.ayf.payment.game.api.entity.*;
import com.ayf.payment.game.api.exception.BusinessException;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.mapper.MerchantConfigMapper;
import com.ayf.payment.game.api.mapper.MerchantSettleRateCustomMapper;
import com.ayf.payment.game.api.mapper.TemplateIdMapper;
import com.ayf.payment.game.api.mapper.TemplateMapper;
import com.ayf.payment.game.api.service.*;
import com.ayf.payment.game.api.type.AdditionalStatus;
import com.ayf.payment.game.api.type.EquipmentStatus;
import com.ayf.payment.game.api.type.Status;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.BeanConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class TemplateServiceImpl implements TemplateService {

    @Resource
    private TemplateMapper templateMapper;

    @Resource
    private MerchantConfigMapper merchantConfigMapper;

    @Resource
    private TemplateAdditionalService templateAdditionalService;

    @Resource
    private TemplateChannelService templateChannelService;

    @Resource
    private TemplateNpcMapService templateNpcMapService;

    @Resource
    private TemplateEquipmentService templateEquipmentService;

    @Resource
    private TemplateCustomizeService templateCustomizeService;

    @Resource
    private TemplateIntegralService templateIntegralService;

    @Resource
    private TemplateEscitationService templateEscitationService;

    @Resource
    private PartitionService partitionService;

    @Resource
    private MerchantSettleRateCustomMapper merchantSettleRateCustomMapper;

    @Resource
    private MerchantConfigService merchantConfigService;

    @Resource
    private MerchantService merchantService;

    @Resource
    private LogOperationService logOperationService;

    @Resource
    TemplateIdMapper templateIdMapper;

    @Override
    public List<TemplateDTO> selectAllTemplate(TemplateSelectCriteria selectCriteria) {
        if (selectCriteria == null) {
            throw new ParameterException("查询分区模板---参数不能为空");
        }
        if (selectCriteria.getMerchantId() == 0) {
            throw new ParameterException("查询分区模板---商户id不能为空");
        }
        if (selectCriteria.getTemplateStatus() == null) {
            throw new ParameterException("查询分区模板---分区状态不能为空");
        }
        return templateMapper.selectAllTemplate(selectCriteria);
    }

    @Override
    public List<TemplateDTO> selectPageTemplate(TemplatePageCriteria selectCriteria){
        if (selectCriteria == null) {
            throw new ParameterException("查询分区模板---参数不能为空");
        }
        if (selectCriteria.getMerchantId() == 0) {
            throw new ParameterException("查询分区模板---商户id不能为空");
        }
        if (selectCriteria.getTemplateStatus() == null) {
            throw new ParameterException("查询分区模板---分区状态不能为空");
        }
        return templateMapper.selectPageTemplate(selectCriteria);
    }

    @Override
    public boolean insertTemplate(TemplateCriteria criteria) {
        if (criteria == null) {
            throw new ParameterException("添加分区模板---参数不能为空");
        }
        if (criteria.getMerchantId() == 0) {
            throw new ParameterException("添加分区模板---商户id不能为空");
        }
        if (StringUtils.isBlank(criteria.getTemplateName())) {
            throw new ParameterException("添加分区模板---分区名称不能为空");
        }

        Template template = BeanConvertUtils.convert(criteria, Template.class);
        TemplateId templateId = new TemplateId();
        templateIdMapper.insert(templateId);
        template.setId(String.valueOf(templateId.getId()));
        templateMapper.insertSelective(template);
        criteria.setId(template.getId());
        addTem(criteria);
        LogOperation logOperation=new LogOperation("添加模版","模版名："+criteria.getTemplateName()+"，操作IP:"+criteria.getOperIp(),"成功", new Date(),criteria.getMerchantId(),template.getId());
        logOperationService.insert(logOperation);
        return true;
    }

    private void addTem(TemplateCriteria criteria) {
        //添加npc信息
        if (criteria.getNpcMapList() != null && criteria.getNpcMapList().size() > 0) {
            List<TemplateNpcMap> npcMapList = BeanConvertUtils.convert(criteria.getNpcMapList(), TemplateNpcMap.class);
            for (TemplateNpcMap npcMap : npcMapList) {
                npcMap.setTemplateId(criteria.getId());
                npcMap.setId(SnowFlakeUtils.getUniqueId());
            }
            templateNpcMapService.insertNpcMaps(npcMapList);
        }
        //添加附加赠送信息
        if (criteria.getAdditionalList() != null && criteria.getAdditionalList().size() > 0) {
            List<TemplateAdditional> additionals = BeanConvertUtils.convert(criteria.getAdditionalList(), TemplateAdditional.class);
            for (TemplateAdditional additional : additionals) {
                additional.setTemplateId(criteria.getId());
                additional.setId(SnowFlakeUtils.getUniqueId());
            }
            templateAdditionalService.insertAdditionals(additionals);
        }
        //添加渠道赠送信息
        if (criteria.getChannelList() != null && criteria.getChannelList().size() > 0) {
            List<TemplateChannel> channels = BeanConvertUtils.convert(criteria.getChannelList(), TemplateChannel.class);
            for (TemplateChannel channel : channels) {
                channel.setTemplateId(criteria.getId());
                channel.setId(SnowFlakeUtils.getUniqueId());
            }
            templateChannelService.insertChannels(channels);
        }
        //添加积分赠送信息
        if (criteria.getIntegralList() != null && criteria.getIntegralList().size() > 0) {
            List<TemplateIntegral> integrals = BeanConvertUtils.convert(criteria.getIntegralList(), TemplateIntegral.class);
            for (TemplateIntegral temp : integrals) {
                temp.setTemplateId(criteria.getId());
                temp.setId(SnowFlakeUtils.getUniqueId());
            }
            templateIntegralService.insertIntegrals(integrals);
        }
        //添加装备赠送信息
        if (criteria.getEquipmentList() != null && criteria.getEquipmentList().size() > 0) {
            List<TemplateEquipment> equipments = BeanConvertUtils.convert(criteria.getEquipmentList(), TemplateEquipment.class);
            for (TemplateEquipment temp : equipments) {
                temp.setTemplateId(criteria.getId());
                temp.setId(SnowFlakeUtils.getUniqueId());
            }
            templateEquipmentService.insertEquipments(equipments);
        }
        //添加自定义模版信息
        if (criteria.getCustomizeList() != null && criteria.getCustomizeList().size() > 0) {
            List<TemplateCustomize> customizes = BeanConvertUtils.convert(criteria.getCustomizeList(), TemplateCustomize.class);
            for (TemplateCustomize temp : customizes) {
                temp.setTemplateId(criteria.getId());
                temp.setId(SnowFlakeUtils.getUniqueId());
                temp.setCreateTime(new Date());
            }
            templateCustomizeService.insertCustomizes(customizes);
        }

        //添加激励赠送信息
        if (criteria.getEscitationList() != null && criteria.getEscitationList().size() > 0) {
            List<TemplateEscitation> excitations = BeanConvertUtils.convert(criteria.getEscitationList(), TemplateEscitation.class);
            for (TemplateEscitation temp : excitations) {
                temp.setTemplateId(criteria.getId());
                temp.setId(SnowFlakeUtils.getUniqueId());
            }
            templateEscitationService.insertExcitations(excitations);
        }
    }

    @Override
    public Template selectTemByTemName(String name, Integer merchantId) {
        if (StringUtils.isBlank(name)) {
            throw new IllegalArgumentException("名称不能为空");
        }
        Template template = new Template();
        template.setTemplateName(name);
        template.setMerchantId(merchantId);
        return templateMapper.selectOne(template);
    }

    @Override
    public TemplateCriteria selectTemById(String id) {
        if (StringUtils.isBlank(id)) {
            throw new ParameterException("查询模板信息时，id不能为空");
        }
        Template template = templateMapper.selectByPrimaryKey(id);
        if (template == null) {
            throw new NullSetException("模板id有误，查询结果为空");
        }
        TemplateCriteria templateCriteria = BeanConvertUtils.convert(template, TemplateCriteria.class);
        //激励赠送信息查询
        List<TemplateEscitation> escitationList = templateEscitationService.selectAllByTemplateId(templateCriteria.getId());
        if (escitationList != null && escitationList.size() > 0) {
            templateCriteria.setEscitationList(BeanConvertUtils.convert(escitationList, TemplateEscitationDTO.class));
        }
        //赠送装备信息查询
        List<TemplateEquipment> equipmentList = templateEquipmentService.selectAllByTemplateId(templateCriteria.getId());
        if (equipmentList != null && equipmentList.size() > 0) {
            templateCriteria.setEquipmentList(BeanConvertUtils.convert(equipmentList, TemplateEquipmentDTO.class));
        }
        //积分赠送查询
        List<TemplateIntegral> integralList = templateIntegralService.selectAllByTemplateId(templateCriteria.getId());
        if (integralList != null && integralList.size() > 0) {
            templateCriteria.setIntegralList(BeanConvertUtils.convert(integralList, TemplateIntegralDTO.class));
        }
        //渠道赠送查询
        List<TemplateChannel> channelList = templateChannelService.selectAllByTemplateId(templateCriteria.getId());
        if (channelList != null && channelList.size() > 0) {
            templateCriteria.setChannelList(BeanConvertUtils.convert(channelList, TemplateChannelDTO.class));
        }
        //附加赠送查询
        List<TemplateAdditional> additionalList = templateAdditionalService.selectAllByTemplateId(templateCriteria.getId());
        if (additionalList != null && additionalList.size() > 0) {
            templateCriteria.setAdditionalList(BeanConvertUtils.convert(additionalList, TemplateAdditionalDTO.class));
        }
        //自定义查询T
        List<TemplateCustomize> customizeList = templateCustomizeService.selectAllByTemplateId(templateCriteria.getId());
        if (customizeList != null && customizeList.size() > 0) {
            templateCriteria.setCustomizeList(BeanConvertUtils.convert(customizeList, TemplateCustomizeDTO.class));
        }
        //npc信息查询
        List<TemplateNpcMap> npcMapList = templateNpcMapService.selectAllByTemplateId(templateCriteria.getId());
        if (npcMapList != null && npcMapList.size() > 0) {
            templateCriteria.setNpcMapList(BeanConvertUtils.convert(npcMapList, TemplateNpcMapDTO.class));
        }
        return templateCriteria;
    }

    @Override
    public boolean updateTemInfo(TemplateCriteria updateCriteria) {
        if (updateCriteria == null) {
            throw new ParameterException("参数不能为空");
        }
        if (StringUtils.isBlank(updateCriteria.getTemplateName())) {
            throw new ParameterException("模板名称不能为空");
        }
       
        updateCriteria.setLastUpdateTime(null);
        Template template =BeanConvertUtils.convert(updateCriteria, Template.class);
        templateMapper.updateByPrimaryKeySelective(template);
        //删除源数据
        templateNpcMapService.delNpcMapByTemId(updateCriteria.getId());
        templateAdditionalService.delAdditionalByTemId(updateCriteria.getId());
        templateChannelService.delChannelByTemId(updateCriteria.getId());
        templateIntegralService.delIntegralByTemId(updateCriteria.getId());
        templateEquipmentService.delEquipmentByTemId(updateCriteria.getId());
        templateCustomizeService.delCustomizeByTemId(updateCriteria.getId());
        templateEscitationService.delEscitationByTemId(updateCriteria.getId());
        //添加新数据
        addTem(updateCriteria);
        LogOperation logOperation=new LogOperation("更新模版","模版名："+updateCriteria.getTemplateName()+"，操作IP:"+updateCriteria.getOperIp(),"成功", new Date(),updateCriteria.getMerchantId(),updateCriteria.getId());
        logOperationService.insert(logOperation);
        return true;
    }

    @Override
    public boolean updateTemStatusById(TemplateCriteria temCriteria) {
        if (temCriteria == null || StringUtils.isBlank(temCriteria.getId())) {
            throw new ParameterException("模板id不能为空");
        }
        if (partitionService.isHavePartitionByTemId(temCriteria.getId())) {
            LogOperation logOperation=new LogOperation("删除模版","有分区在引用该模板("+temCriteria.getTemplateName()+")，操作IP:"+temCriteria.getOperIp(),"失败", new Date(),temCriteria.getMerchantId(),temCriteria.getId());
            logOperationService.insert(logOperation);
            throw new BusinessException(-3, "删除失败---有分区在引用该模板");
        }
        Template template = new Template();
        template.setId(temCriteria.getId());
        template.setTemplateStatus(Status.PROHIBIT);
        if(templateMapper.updateByPrimaryKeySelective(template) > 0){
            LogOperation logOperation=new LogOperation("删除模版","删除成功("+temCriteria.getTemplateName()+")，操作IP:"+temCriteria.getOperIp(),"成功", new Date(),temCriteria.getMerchantId(),temCriteria.getId());
            logOperationService.insert(logOperation);
            return true;
        }else{
            LogOperation logOperation=new LogOperation("删除模版","删除失败("+temCriteria.getTemplateName()+")，操作IP:"+temCriteria.getOperIp(),"失败", new Date(),temCriteria.getMerchantId(),temCriteria.getId());
            logOperationService.insert(logOperation);
            return false;
        }

    }

    @Override
    public List<GameTemplateDTO> selectTemByGameId(TemplateGameSelectCriteria tgc) {
        if (tgc == null || StringUtils.isBlank(tgc.getGameId())) {
            throw new ParameterException("游戏id不能为空");
        }
        if (tgc.getMerchantId() == null) {
            throw new ParameterException("商户id不能为空");
        }
        Example example = new Example(Template.class);
        example.and().andEqualTo("gameId",tgc.getGameId())
        .andEqualTo("merchantId",tgc.getMerchantId())
        .andEqualTo("templateStatus",Status.ENABLE);
        example.orderBy("createTime").desc();
        List<Template> templateList = templateMapper.selectByExample(example);
        return BeanConvertUtils.convert(templateList, GameTemplateDTO.class);
    }

    @Override
    public ParAndTemInfoDTO selectParAndTemInfo(String partitionId) {
        if (StringUtils.isBlank(partitionId)) {
            throw new ParameterException("分区id不能为空");
        }
        ParAndTemInfoDTO dto = templateMapper.selectParAndTemInfo(partitionId);
        if (dto == null) {
            MerchantConfig merchantConfig = merchantConfigMapper.selectConfigByPartitionId(partitionId);
            String msg="";
            if(null!=merchantConfig){
                if(!StringUtils.isEmpty(merchantConfig.getCustomerQq())){
                    msg="，联系QQ："+merchantConfig.getCustomerQq();
                }else {
                    Merchant merchant= merchantService.find(merchantConfig.getMerchantId());
                    if (!StringUtils.isEmpty(merchant.getQq())) {
                        msg = "，联系QQ：" + merchant.getQq();
                    }
                }
            }
            throw new ParameterException("分区不存在"+msg);
        }
        SettleConfigDTO settleConfigDTO = merchantConfigService.selectConfigByPartitionId(partitionId);
        if (settleConfigDTO!=null) {
            dto.setRechargeMinAmt(settleConfigDTO.getMinRechargeAmount());
        }
        //激励赠送信息查询
        List<TemplateEscitation> escitationList = templateEscitationService.selectAllByTemplateId(dto.getTemplateId());
        if (escitationList != null && escitationList.size() > 0) {
            dto.setEscitationList(BeanConvertUtils.convert(escitationList, TemplateEscitationDTO.class));
        }
        //赠送装备信息查询
        if (!EquipmentStatus.CLOSE.equals(dto.getEquipmentStatus())) {
            List<TemplateEquipment> equipmentList = templateEquipmentService.selectAllByTemplateId(dto.getTemplateId());
            if (equipmentList != null && equipmentList.size() > 0) {
                dto.setEquipmentList(BeanConvertUtils.convert(equipmentList, TemplateEquipmentDTO.class));
            }
        }
        //积分赠送查询
        List<TemplateIntegral> integralList = templateIntegralService.selectAllByTemplateId(dto.getTemplateId());
        if (integralList != null && integralList.size() > 0) {
            integralList.removeIf(integral -> AdditionalStatus.CLOSE.equals(integral.getIntegralStatus()));
            dto.setIntegralList(BeanConvertUtils.convert(integralList, TemplateIntegralDTO.class));
        }
        //渠道赠送查询
        List<TemplateChannelDTO> channelList = merchantSettleRateCustomMapper.selectChannelGive(dto.getMerchantId(), dto.getTemplateId());
        dto.setChannelList(channelList);
        //附加赠送查询
        List<TemplateAdditional> additionalList = templateAdditionalService.selectAllByTemplateId(dto.getTemplateId());
        if (additionalList != null && additionalList.size() > 0) {
            additionalList.removeIf(additional -> AdditionalStatus.CLOSE.equals(additional.getAdditionalStatus()));
            dto.setAdditionalList(BeanConvertUtils.convert(additionalList, TemplateAdditionalDTO.class));
        }
        return dto;
    }

    @Override
    public ParAndTemInfoDTO selectTemInfo(String partitionId) {
        return templateMapper.selectParAndTemInfoAll(partitionId);
    }
}


